import React, { useState, useEffect, useRef, useCallback } from "react";
import { Service } from "../api/services/Service";
import type { VidVideo_ } from "../api/models/VidVideo_";
import type { VidVideoCompilation_ } from "../api/models/VidVideoCompilation_";
import "./VideoList.css";
import {
  canWatchVideo,
  checkAndRefreshVipStatus,
  getToken,
} from "../utils/auth";
import { message, Modal } from "antd";
import { useUser } from "../stores/userStore";

interface VideoListProps {
  onVideoClick: (video: VidVideo_) => void;
  onLoginClick?: () => void;
  onLogout?: () => void;
}

const VideoList: React.FC<VideoListProps> = ({
  onVideoClick,
  onLoginClick,
  onLogout,
}) => {
  const { userInfo, refreshUserInfo } = useUser();
  const [videos, setVideos] = useState<VidVideo_[]>([]);
  const [compilations, setCompilations] = useState<VidVideoCompilation_[]>([]);
  const [activeTab, setActiveTab] = useState<string>("all");
  const [loading, setLoading] = useState<boolean>(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [isModalVisible, setIsModalVisible] = useState(false);

  // 用于观察最后一个视频元素的ref
  const observer = useRef<IntersectionObserver>();
  const lastVideoElementRef = useCallback(
    (node: HTMLDivElement) => {
      if (loading) return;
      if (observer.current) observer.current.disconnect();
      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasMore) {
          setPage((prevPage) => prevPage + 1);
        }
      });
      if (node) observer.current.observe(node);
    },
    [loading, hasMore]
  );

  useEffect(() => {
    loadCompilations();
    // 初始化时重置状态
    setVideos([]);
    setPage(1);
    setHasMore(true);
  }, []);

  useEffect(() => {
    // 页面刷新时获取最新用户信息
    if (userInfo?.id) {
      refreshUserInfo();
    }
  }, [userInfo?.id]);

  // 监听页码变化，加载对应页面的视频
  useEffect(() => {
    if (page === 1) {
      setVideos([]); // 重置视频列表
    }
    loadVideos(activeTab, page);
  }, [page, activeTab]);

  const handleVideoClick = async (video: VidVideo_) => {
    // 获取最新的用户信息
    const latestUserInfo = await refreshUserInfo();

    // 使用最新的用户信息检查是否可以观看视频
    if (!canWatchVideo(video, latestUserInfo)) {
      // 如果用户已登录但权限不足，尝试刷新用户状态
      if (latestUserInfo) {
        try {
          message.loading("正在检查您的会员状态...", 0);
          const hasVipAccess = await checkAndRefreshVipStatus();
          message.destroy();

          if (hasVipAccess) {
            // 刷新后有权限，重新获取用户信息
            const refreshedUserInfo = await refreshUserInfo();
            message.success("检测到您已是VIP会员，正在为您播放视频");
            // 使用刷新后的用户信息再次检查权限
            if (canWatchVideo(video, refreshedUserInfo)) {
              onVideoClick(video);
            } else {
              setTimeout(() => {
                window.location.reload();
              }, 1000);
            }
            return;
          } else {
            message.error("该视频需要VIP会员才能观看");
            return;
          }
        } catch (error) {
          message.destroy();
          message.error("检查会员状态失败，该视频需要VIP会员才能观看");
          return;
        }
      } else {
        // 用户未登录，跳转到登录页面
        if (onLoginClick) {
          onLoginClick();
        }
        return;
      }
    }

    onVideoClick(video);
  };

  // 处理tab切换
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const copyWechatId = async () => {
    try {
      await navigator.clipboard.writeText("Zeran0817");
      message.success("微信号已复制到剪贴板");
    } catch (err) {
      // 降级方案：使用传统方法复制
      const textArea = document.createElement("textarea");
      textArea.value = "Zeran0817";
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      message.success("微信号已复制到剪贴板");
    }
  };

  // 处理tab切换
  const handleTabClick = (tabId: string) => {
    setActiveTab(tabId);
    setPage(1);
    setVideos([]);
    setHasMore(true);
  };

  const loadCompilations = async () => {
    try {
      const response = await Service.compilationListUsingPost1();
      if (response.data?.records) {
        setCompilations(response.data.records);
      }
    } catch (error) {
      console.error("加载合集失败:", error);
    }
  };

  const loadVideos = async (compilationId?: string, currentPage?: number) => {
    setLoading(true);
    try {
      const params: any = {
        current: currentPage || page,
        size: 20,
      };

      // 如果不是"全部"，则添加合集ID筛选
      if (compilationId && compilationId !== "all") {
        params.compilationId = compilationId;
      }

      const response = await Service.videoListUsingPost1(params);
      if (response.data?.records) {
        const newVideos = response.data.records;

        if (currentPage === 1 || page === 1) {
          // 第一页或重新加载时，直接设置视频列表
          setVideos(newVideos);
        } else {
          // 后续页面，追加到现有列表
          setVideos((prevVideos) => {
            // 使用Map去重，避免重复数据
            const videoMap = new Map();
            [...prevVideos, ...newVideos].forEach((video) => {
              videoMap.set(video.id, video);
            });
            return Array.from(videoMap.values());
          });
        }

        // 如果返回的数据少于请求的数量，说明没有更多数据了
        setHasMore(newVideos.length === 20);
      }
    } catch (error) {
      console.error("加载视频失败:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="video-list-container">
      {/* 顶部导航栏 */}
      <div className="header">
        {userInfo ? (
          <div className="user-info">
            <span>
              欢迎，{userInfo.nickName || "用户"}
              &nbsp;&nbsp;
              {userInfo.vipStatus && <span className="vip-badge">VIP</span>}
            </span>

            <button className="logout-btn" onClick={onLogout}>
              退出
            </button>
          </div>
        ) : (
          <button className="login-btn" onClick={onLoginClick}>
            登录
          </button>
        )}
      </div>

      {/* 顶部公告  onClick={showModal} 点此升级为会员*/}
      <div className="announcement" onClick={showModal}>
        <span>公告：点此升级为会员</span>
      </div>

      <Modal
        title="会员开通指引"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null} // 不显示底部按钮
        centered // 居中显示
        width={600}
      >
        <div className="modal-content">
          <div className="intro-section">
            <h3>小叔观影全网同名，题材敏感审核艰难</h3>
            <h3>自建小站自由播放，我说痛快你听痛快</h3>
          </div>

          <div className="trial-section">
            <h2>试看说明</h2>
            <h3>本站前4个视频为试看视频</h3>
          </div>

          <div className="price-section">
            <h2>会员价格</h2>
            <h3>
              全网会员统一价格 <span className="price">50/月(31天)</span>
            </h3>
          </div>

          <div className="contact-section">
            <h2>开通方式</h2>
            <h3>办理新会员，续费老会员</h3>
            <h3>
              请先完成注册后，然后联系微信：
              <strong className="wechat-id" onClick={copyWechatId}>
                Zeran0817
              </strong>{" "}
              (注明来意)
            </h3>
          </div>

          <div className="notice-section">
            <div className="notice-box">
              <p>开通会员后，请退出重新登录以刷新状态</p>
            </div>
          </div>
        </div>
      </Modal>

      {/* 标签页导航 */}
      <div className="tabs-container">
        {/* 全部选项 */}
        <button
          className={`tab-button ${activeTab === "all" ? "active" : ""}`}
          onClick={() => handleTabClick("all")}
        >
          全部
        </button>
        {/* 合集选项 */}
        {compilations.map((tab: any) => (
          <button
            key={tab.id}
            className={`tab-button ${activeTab === tab.id ? "active" : ""}`}
            onClick={() => handleTabClick(tab.id)}
          >
            {tab.name}
          </button>
        ))}
      </div>

      {/* 视频列表 */}
      <div className="video-grid">
        {videos.length === 0 && loading ? (
          <div className="loading">加载中...</div>
        ) : (
          videos.map((video, index) => {
            // 如果是最后一个视频，添加ref用于触发加载更多
            if (videos.length === index + 1) {
              return (
                <div
                  ref={lastVideoElementRef}
                  key={video.id}
                  className="video-card"
                  onClick={() => handleVideoClick(video)}
                >
                  <div className="video-thumbnail">
                    <img
                      src={`/api/file/download/img?fileName=${
                        video.coverId
                      }&token=${getToken()}`}
                      alt={video.title}
                    />
                    <div className="play-button">
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="white"
                      >
                        <path d="M8 5v14l11-7z" />
                      </svg>
                    </div>
                  </div>
                  <div className="video-info">
                    <h3 className="video-title">{video.title}</h3>
                    <p className="video-description">
                      {video.freeState ? "免费观看" : "VIP专享"}
                    </p>
                  </div>
                </div>
              );
            } else {
              return (
                <div
                  key={video.id}
                  className="video-card"
                  onClick={() => handleVideoClick(video)}
                >
                  <div className="video-thumbnail">
                    <img
                      src={`/api/file/download/img?fileName=${
                        video.coverId
                      }&token=${getToken()}`}
                      alt={video.title}
                    />
                    <div className="play-button">
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="white"
                      >
                        <path d="M8 5v14l11-7z" />
                      </svg>
                    </div>
                  </div>
                  <div className="video-info">
                    <h3 className="video-title">{video.title}</h3>
                    <p className="video-description">
                      {video.freeState ? "免费观看" : "VIP专享"}
                    </p>
                  </div>
                </div>
              );
            }
          })
        )}

        {/* 加载更多状态提示 */}
        {loading && videos.length > 0 && (
          <div className="loading-more">正在加载更多...</div>
        )}

        {/* 没有更多数据提示 */}
        {!hasMore && videos.length > 0 && (
          <div className="no-more">没有更多视频了</div>
        )}
      </div>
    </div>
  );
};

export default VideoList;
